package com.ruoyi.system.utils;

import com.ruoyi.system.pojo.vms.SkuEntity;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
 * Description:
 *
 * @author JourWon
 * @date Created on 2025/5/14
 */
public class ExcelUtil {

    public static List<SkuEntity> parseSkuExcel(MultipartFile file) throws IOException {
        List<SkuEntity> skuList = new ArrayList<>();

        try (InputStream is = file.getInputStream();
             Workbook workbook = new XSSFWorkbook(is)) {

            Sheet sheet = workbook.getSheetAt(0);
            Iterator<Row> rows = sheet.iterator();

            // 跳过标题行
            if (rows.hasNext()) {
                rows.next();
            }

            while (rows.hasNext()) {
                Row currentRow = rows.next();
                SkuEntity sku = new SkuEntity();

                // 解析各列数据
                sku.setSkuName(getCellStringValue(currentRow.getCell(0)));
                sku.setSkuImage(getCellStringValue(currentRow.getCell(1)));
                sku.setPrice((int) getCellNumericValue(currentRow.getCell(2)));
                sku.setClassId((int) getCellNumericValue(currentRow.getCell(3)));
                sku.setUnit(getCellStringValue(currentRow.getCell(4)));
                sku.setBrandName(getCellStringValue(currentRow.getCell(5)));

                skuList.add(sku);
            }
        }

        return skuList;
    }

    private static String getCellStringValue(Cell cell) {
        if (cell == null) return "";

        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                return String.valueOf((int) cell.getNumericCellValue());
            default:
                return "";
        }
    }

    private static double getCellNumericValue(Cell cell) {
        if (cell == null) return 0;

        switch (cell.getCellType()) {
            case NUMERIC:
                return cell.getNumericCellValue();
            case STRING:
                try {
                    return Double.parseDouble(cell.getStringCellValue());
                } catch (NumberFormatException e) {
                    return 0;
                }
            default:
                return 0;
        }
    }
}
